<?php
/**
 * Created by PhpStorm.
 * User: 丶晓
 * Date: 2017/9/20
 * Time: 11:43
 */

namespace app\common\Contact;

use app\common\Base;
use think\Cookie;
use think\Session;

class SMS extends Base
{

    // +++++++++++++++++++++++++++++++++++++++++++++++++++++
    // |   赛邮 · 云通信 发送短信验证码  @Xiao
    // |   验证使用 Session:get('sms_code');
    // |   默认 过期时间 = 600 秒 = 10 分钟
    // |   最低 3分钟 允许重新发送一次
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++
    public function send_valiCode($phone, $validTime = 600)
    {
        if (Cookie::has('sms_id') and date('U') - Session::get('sms_time') < 180) {
            return false;
        }
        $code = rand(10000, 99999);
        $sms_code = json_encode(['code' => $code]);
        $url = 'https://api.mysubmail.com/message/xsend.json';
        $data = "appid=14520&to=" . $phone . "&project=f7Br63&signature=fd766e9534c72a7856ab962bf8fc9059&vars=" . $sms_code;
        $res = $this->_requestPost($url, $data);
        $result = json_decode($res, true);
        if ($result['status'] == 'success') {
            Cookie::set('sms_id', $result['send_id'], $validTime);
            Session::set('sms_code', $code);
            Session::set('sms_id', $result['send_id']);
            Session::set('sms_time', date('U'));
            return $result['send_id'];
        }
        return false;
    }

    // +++++++++++++++++++++++++++++++++++++++++++++++++++++
    // |
    // |  @Xiao 检测短信验证码  fun = send_valiCode()
    // |
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++
    public function check_smsCode($code)
    {
        if (!isset($code) or empty($code)) {
            return false;
        }
        if (Cookie::has('sms_id') and Cookie::get('sms_id') == Session::get('sms_id')) {
            if (Session::get('sms_code') == $code) {
                return true;
            }
        }
        return false;
    }


}